"""搜索相关路由（使用Elasticsearch）"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
import json
import logging

# 先创建logger
logger = logging.getLogger(__name__)

from database import get_db
from models.models import Content, User
# Elasticsearch可选导入
try:
    from config.es_client import search_content, create_content_index, sync_all_contents_to_es, check_es_connection
    ES_AVAILABLE = True
except ImportError:
    logger.warning("Elasticsearch未安装，将使用MySQL搜索")
    ES_AVAILABLE = False

router = APIRouter(prefix="/api/search", tags=["搜索"])


@router.post("/content")
async def search_content_api(
    body: dict,
    db: Session = Depends(get_db)
):
    """
    搜索内容（使用Elasticsearch）
    
    参数:
        keyword: 搜索关键词
        limit: 返回结果数量限制
    """
    try:
        keyword = body.get('keyword', '')
        limit = body.get('limit', 20)
        
        # 如果没有关键词，返回空结果
        if not keyword or not keyword.strip():
            return JSONResponse({
                "success": True,
                "data": [],
                "count": 0
            })
        
        keyword = keyword.strip()
        
        # 使用Elasticsearch搜索（如果可用）
        es_results = []
        if ES_AVAILABLE:
            try:
                es_results = search_content(keyword, limit)
            except Exception as e:
                logger.warning(f"ES搜索失败: {e}")
                es_results = []
        
        # 如果ES没有结果，回退到MySQL搜索
        if not es_results:
            logger.warning("ES搜索无结果，使用MySQL搜索")
            all_contents = db.query(Content).filter(Content.status == 1).all()
            
            matched_contents = []
            for content in all_contents:
                if isinstance(content.tags, str):
                    tags = json.loads(content.tags) if content.tags else []
                else:
                    tags = content.tags or []
                
                # 简单匹配
                if (keyword.lower() in (content.title or '').lower() or 
                    keyword.lower() in (content.content or '').lower() or
                    keyword.lower() in str(tags).lower()):
                    matched_contents.append(content)
            
            # 按点赞数排序
            matched_contents.sort(key=lambda x: x.like_count, reverse=True)
            es_results = matched_contents[:limit]
        
        # 构建响应
        result = []
        for item in es_results:
            try:
                # 如果是ES结果，直接使用
                if 'id' in item and 'author_nickname' in item:
                    result.append(item)
                else:
                    # 如果是MySQL结果，需要补充作者信息
                    content = item
                    author = db.query(User).filter(User.id == content.user_id).first()
                    
                    media_urls = []
                    if content.media_urls:
                        if isinstance(content.media_urls, list):
                            media_urls = content.media_urls
                        elif isinstance(content.media_urls, str):
                            try:
                                media_urls = json.loads(content.media_urls)
                            except:
                                media_urls = []
                    
                    tags = []
                    if content.tags:
                        if isinstance(content.tags, list):
                            tags = content.tags
                        elif isinstance(content.tags, str):
                            try:
                                tags = json.loads(content.tags)
                            except:
                                tags = []
                    
                    result.append({
                        "id": content.id,
                        "user_id": content.user_id,
                        "title": content.title or '无标题',
                        "content": content.content or '',
                        "media_urls": media_urls,
                        "tags": tags,
                        "like_count": content.like_count or 0,
                        "view_count": content.view_count or 0,
                        "collect_count": content.collect_count or 0,
                        "comment_count": content.comment_count or 0,
                        "created_at": content.created_at.isoformat() if content.created_at else None,
                        "author_nickname": author.nickname if author else '游客',
                        "author_avatar": author.avatar_url if author else None
                    })
            except Exception as e:
                logger.error(f"处理搜索结果时出错: {e}")
                continue
        
        return JSONResponse({
            "success": True,
            "data": result,
            "count": len(result),
            "keyword": keyword
        })
        
    except Exception as e:
        logger.error(f"搜索失败: {e}")
        import traceback
        traceback.print_exc()
        return JSONResponse({
            "success": False,
            "message": f"搜索失败: {str(e)}",
            "data": []
        }, status_code=500)


@router.post("/sync")
async def sync_to_es(db: Session = Depends(get_db)):
    """同步数据到Elasticsearch"""
    try:
        # 检查ES连接
        if not ES_AVAILABLE or not check_es_connection():
            return JSONResponse({
                "success": False,
                "message": "Elasticsearch未连接，请先启动ES服务"
            }, status_code=500)
        
        # 创建索引
        create_content_index()
        
        # 同步数据
        sync_all_contents_to_es(db)
        
        return JSONResponse({
            "success": True,
            "message": "同步成功"
        })
        
    except Exception as e:
        logger.error(f"同步失败: {e}")
        return JSONResponse({
            "success": False,
            "message": f"同步失败: {str(e)}"
        }, status_code=500)

